const bcrypt = require('bcryptjs')

const { getUserinfo } = require('../service/user.service')
const {
  userFormateError,
  userAlreadyExited,
  userRegiisterError,
  userDoesNotExist,
  userLoginError,
  invarlidPassword,
  verifyPassError
} = require('../constant/err.type')

const userValidator = async (ctx, next) => {
  const { user_name, password } = ctx.request.body
  // 合法性
  if (!user_name || !password) {
    console.error('用户名或密码为空', ctx.request.body);
    ctx.app.emit('error', userFormateError, ctx)
    return
  }
  await next()
}
const verifyUser = async (ctx, next) => {

  const { user_name } = ctx.request.body

  try {
    const res = await getUserinfo({ user_name })
    if (res) {
      console.error('用户名已经存在', { user_name });
      ctx.app.emit('error', userAlreadyExited, ctx)
      return
    }

  } catch (err) {
    console.error('获取用户信息错误', err);
    ctx.app.emit('error', userRegiisterError, ctx)
    return
  }
  await next()
}
const crpytPassword = async (ctx, next) => {

  const { password } = ctx.request.body

  const salt = bcrypt.genSaltSync(10);

  // hash保存的是密文
  const hash = bcrypt.hashSync(password, salt)

  ctx.request.body.password = hash

  await next()
}
const verifyLogin = async (ctx, next) => {
  // 判断用户是否存在
  const { user_name, password } = ctx.request.body

  try {
    const res = await getUserinfo({ user_name })

    if (!res) {
      console.error("用户不存在", { user_name });
      ctx.app.emit('error', userDoesNotExist, ctx)
      return
    }
    // 密码校验
    if (!bcrypt.compareSync(password, res.password)) {
      console.error('密码不匹配', { password })
      ctx.app.emit('error', invarlidPassword, ctx)
      return
    }
  } catch (err) {
    console.error(err)
    ctx.app.emit('error', userLoginError, ctx)
    return
  }
  await next()

}
const verifyPassword = async (ctx, next) => {
  const id = ctx.state.user.id
  const { password } = ctx.request.body

  const res = await getUserinfo({ id })

  if (bcrypt.compareSync(password, res.password)) {
    console.error('新旧密码相同', { password })
    ctx.app.emit('error', verifyPassError, ctx)
    return
  }
  await next()
}

module.exports = {
  userValidator,
  verifyUser,
  crpytPassword,
  verifyLogin,
  verifyPassword,
}